import tinymce from 'tinymce/tinymce'

(function() {
  (function() {
    'use strict'

    var global = tinymce.util.Tools.resolve('tinymce.PluginManager')

    var youkuclick = function(editor) {
      editor.windowManager.open({
        title: '插入优酷视频',
        body: [{
          type: 'textbox',
          name: 'videourl',
          label: '视频地址'
        }],
        onsubmit(e) {
          var d = document.createElement('div')
          d.innerHTML = e.data.videourl
          if (d.childNodes.length === 1 && d.childNodes[0].src) {
            // http://player.youku.com/embed/XMzY4NTU4MTMwNA==
            const html = `<div style="width: 100%; height: 300px;"><iframe style="width: 100%; height: 100%;" src="${d.childNodes[0].src}" frameborder="0" allowfullscreen=""></iframe></div>`
            // Insert content when the window form is submitted
            editor.insertContent(html)
          }
        }
      })
    }

    global.add('youku', function(editor) {
      editor.addButton('youku', {
        text: '',
        tooltip: '插入优酷视频',
        icon: 'media',
        onclick() {
          // Open window
          youkuclick(editor)
        }
      })

      // Adds a menu item to the tools menu
      editor.addMenuItem('youku', {
        text: '插入优酷视频',
        context: 'insert',
        icon: 'media',
        onclick() {
          // Open window with a specific url
          youkuclick(editor)
        }
      })

      return {
        getMetadata() {
          return {
            name: '优酷视频插件',
            url: '523218882#qq.com'
          }
        }
      }
    })

    function Plugin() {
    }

    return Plugin
  }())
})()
